const API_URL = '/api/file';
const CHUNK_SIZE = 1024 * 1024; // 1MB
const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB

let fileList = [];
let filteredFileList = [];
let currentFilter = 'all';

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
    fetchFileList();
    setupDragAndDrop();
    setupFilterButtons();
});

// 设置拖放上传功能
function setupDragAndDrop() {
    const dropArea = document.getElementById('dropArea');
    const uploadSection = document.getElementById('uploadSection');

    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    ['dragenter', 'dragover'].forEach(eventName => {
        dropArea.addEventListener(eventName, () => {
            uploadSection.classList.add('drag-over');
        }, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, () => {
            uploadSection.classList.remove('drag-over');
        }, false);
    });

    dropArea.addEventListener('drop', (e) => {
        const dt = e.dataTransfer;
        const file = dt.files[0]; // 只处理第一个文件
        if (file) {
            document.getElementById('fileInput').files = dt.files;
            validateAndProcessFile(file);
            showSelectedFilePreview(file);
        }
    }, false);

    // 文件选择事件
    document.getElementById('fileInput').addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
            validateAndProcessFile(file);
            showSelectedFilePreview(file);
        }
    });
}

// 设置过滤按钮
function setupFilterButtons() {
    const filterButtons = document.querySelectorAll('.filter-btn');
    filterButtons.forEach(button => {
        button.addEventListener('click', () => {
            filterButtons.forEach(btn => btn.classList.remove('active'));
            button.classList.add('active');
            currentFilter = button.getAttribute('data-type');
            applyFilters();
        });
    });
}

// 验证并处理文件
function validateAndProcessFile(file) {
    // 检查文件大小
    if (file.size > MAX_FILE_SIZE) {
        showStatusMessage(`文件过大，最大允许 ${formatSize(MAX_FILE_SIZE)}`, true);
        return false;
    }

    // 显示文件信息
    showProgressText(`已选择: ${file.name} (${formatSize(file.size)})`);
    return true;
}

// 显示进度文本
function showProgressText(text) {
    const progressText = document.getElementById('progressText');
    progressText.textContent = text;
    progressText.style.display = 'block';
}

// 获取文件列表
async function fetchFileList() {
    try {
        const response = await fetch(`${API_URL}/list`);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        // 确保返回的是数组
        if (result && result.data && Array.isArray(result.data)) {
            fileList = result.data;
        } else {
            fileList = [];
            console.error('API返回的数据格式不正确:', result);
        }
        
        applyFilters();
    } catch (error) {
        console.error('获取文件列表失败:', error);
        showStatusMessage('获取文件列表失败: ' + error.message, true);
        fileList = [];
        filteredFileList = [];
        renderFileList();
    }
}

// 应用过滤条件
function applyFilters(searchTerm = '') {
    if (!searchTerm) {
        searchTerm = document.getElementById('searchInput').value.toLowerCase();
    }
    
    filteredFileList = fileList.filter(file => {
        // 搜索条件
        const matchesSearch = file.originalName.toLowerCase().includes(searchTerm);
        
        // 类型过滤
        let matchesType = true;
        if (currentFilter !== 'all') {
            matchesType = file.fileType === currentFilter;
        }
        
        return matchesSearch && matchesType;
    });
    
    renderFileList();
}

// 渲染文件列表
function renderFileList() {
    const tbody = document.querySelector('#fileListTable tbody');
    tbody.innerHTML = '';

    if (filteredFileList.length === 0) {
        tbody.innerHTML = '<tr><td colspan="5" class="text-center py-4">没有找到文件</td></tr>';
        return;
    }

    filteredFileList.forEach(file => {
        const tr = document.createElement('tr');
        const createTime = file.createTime ? new Date(file.createTime).toLocaleString() : '未知';
        
        tr.innerHTML = `
            <td class="file-name">
                <i class="bi ${getFileIcon(file.fileType, file.fileExt)} file-icon"></i>
                <span>${file.originalName}</span>
            </td>
            <td>${formatSize(file.fileSize)}</td>
            <td>${file.fileType || '未知'}</td>
            <td>${createTime}</td>
            <td class="file-actions">
                <button class="btn btn-sm btn-outline-primary" onclick="previewFile(${file.id})">预览</button>
                <button class="btn btn-sm btn-info" onclick="downloadFile(${file.id})">下载</button>
                <button class="btn btn-sm btn-danger" onclick="deleteFile(${file.id})">删除</button>
            </td>
        `;
        tbody.appendChild(tr);
    });
}

// 获取文件图标
function getFileIcon(fileType, fileExt) {
    if (fileType === 'Image') return 'bi-file-earmark-image';
    if (fileType === 'PDF') return 'bi-file-earmark-pdf';
    
    // 根据扩展名进一步细分
    if (fileExt) {
        const ext = fileExt.toLowerCase();
        if (['doc', 'docx'].includes(ext)) return 'bi-file-earmark-word';
        if (['xls', 'xlsx'].includes(ext)) return 'bi-file-earmark-excel';
        if (['ppt', 'pptx'].includes(ext)) return 'bi-file-earmark-ppt';
        if (['mp4', 'avi', 'mov', 'wmv', 'flv'].includes(ext)) return 'bi-file-earmark-play';
        if (['mp3', 'wav', 'ogg', 'aac'].includes(ext)) return 'bi-file-earmark-music';
        if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return 'bi-file-earmark-zip';
        if (['txt', 'log', 'md'].includes(ext)) return 'bi-file-earmark-text';
    }
    
    return 'bi-file-earmark';
}

// 格式化文件大小
function formatSize(bytes) {
    if (!bytes || bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 显示状态消息
function showStatusMessage(message, isError = false, duration = 5000) {
    const statusElement = document.getElementById('statusMessage');
    statusElement.textContent = message;
    statusElement.className = 'status-message ' + (isError ? 'error' : 'success');
    statusElement.style.display = 'block';
    
    // 添加图标
    const iconClass = isError ? 'bi-exclamation-circle' : 'bi-check-circle';
    statusElement.innerHTML = `<i class="bi ${iconClass} me-2"></i>${message}`;
    
    // 如果duration为0，则不自动隐藏
    if (duration > 0) {
        setTimeout(() => {
            statusElement.style.display = 'none';
        }, duration);
    }
}

// 上传文件
async function uploadFile() {
    const fileInput = document.getElementById('fileInput');
    const file = fileInput.files[0];
    
    if (!file) {
        showStatusMessage('请先选择文件', true);
        return;
    }

    if (!validateAndProcessFile(file)) {
        return;
    }

    const formData = new FormData();
    formData.append('file', file);

    try {
        // 显示进度条
        const progressBar = document.querySelector('.progress-inner');
        const progressContainer = document.getElementById('uploadProgress');
        progressContainer.style.display = 'block';
        progressBar.style.width = '0%';
        showProgressText('上传中...');
        
        const response = await fetch(`${API_URL}/upload`, {
            method: 'POST',
            body: formData
        });

        if (!response.ok) {
            // 处理400或500错误状态码
            if (response.status === 400 || response.status === 500) {
                const errorData = await response.json();
                throw new Error(errorData.message || `上传失败: ${response.status}`);
            } else {
                throw new Error(`上传失败: ${response.status}`);
            }
        }

        const result = await response.json();
        if (result.code === 200) {
            showStatusMessage('文件上传成功');
            progressBar.style.width = '100%';
            showProgressText('上传完成');
            fetchFileList();
        } else {
            throw new Error(result.message || '上传失败');
        }
    } catch (error) {
        showStatusMessage('上传失败: ' + error.message, true);
        // 隐藏取消按钮
        if (cancelBtn) {
            cancelBtn.style.display = 'none';
        }
    }
    // 重置上传状态
    isUploading = true;
}

// 分片上传
async function uploadFileInChunks() {
    const fileInput = document.getElementById('fileInput');
    const file = fileInput.files[0];
    
    if (!file) {
        showStatusMessage('请先选择文件', true);
        return;
    }

    if (!validateAndProcessFile(file)) {
        return;
    }

    const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
    let uploadedChunks = 0;
    let isUploading = true;

    // 显示进度条
    const progressBar = document.querySelector('.progress-inner');
    const progressContainer = document.getElementById('uploadProgress').parentElement;
    progressContainer.style.display = 'block';
    progressBar.style.width = '0%';
    
    // 添加取消按钮
    let cancelBtn = document.getElementById('cancelUploadBtn');
    if (!cancelBtn) {
        cancelBtn = document.createElement('button');
        cancelBtn.id = 'cancelUploadBtn';
        cancelBtn.className = 'btn btn-danger ms-2';
        cancelBtn.innerHTML = '取消上传';
        const uploadBtns = document.querySelector('.col-md-6:first-child');
        uploadBtns.appendChild(cancelBtn);
    } else {
        cancelBtn.style.display = 'inline-block';
    }
    
    cancelBtn.onclick = () => {
        isUploading = false;
        showStatusMessage('上传已取消', false);
        showProgressText('上传已取消');
        cancelBtn.style.display = 'none';
    };

    try {
        // 计算文件MD5
        showProgressText('计算文件特征值...');
        let fileHash;
        try {
            if (!isUploading) throw new Error('用户取消了上传');
            fileHash = await calculateFileHash(file);
        } catch (error) {
            throw new Error('计算文件特征值失败: ' + error.message);
        }
        
        // 检查文件是否已存在（秒传）
        if (!isUploading) throw new Error('用户取消了上传');
        const checkResponse = await fetch(`${API_URL}/check?md5=${fileHash}`);
        const checkResult = await checkResponse.json();
        
        if (checkResponse.ok && checkResult.code === 200 && checkResult.data) {
            // 文件已存在，直接显示成功
            showStatusMessage('文件已存在，秒传成功');
            progressBar.style.width = '100%';
            showProgressText('上传完成');
            cancelBtn.style.display = 'none';
            fetchFileList();
            return;
        }
        
        // 上传分片
        for (let i = 0; i < totalChunks; i++) {
            if (!isUploading) throw new Error('用户取消了上传');
            
            const start = i * CHUNK_SIZE;
            const end = Math.min(start + CHUNK_SIZE, file.size);
            const chunk = file.slice(start, end);

            const formData = new FormData();
            formData.append('file', chunk);
            formData.append('chunkNumber', i);
            formData.append('totalChunks', totalChunks);
            formData.append('fileMd5', fileHash);
            formData.append('fileName', file.name);
            formData.append('totalSize', file.size);
            formData.append('originalFilename', file.name);
            formData.append('chunkSize', chunk.size);

            const response = await fetch(`${API_URL}/uploadChunk`, {
                method: 'POST',
                body: formData
            });

            if (response.ok) {
                const resultData = await response.json();
                // 处理400或500错误状态码
                if (resultData.code === 400 || resultData.code === 500) {
                    throw new Error(resultData.message || `分片上传失败: ${resultData.code}`);
                }
            }

            uploadedChunks++;
            const progress = Math.round((uploadedChunks / totalChunks) * 100);
            progressBar.style.width = `${progress}%`;
            showProgressText(`上传中: ${progress}% (${uploadedChunks}/${totalChunks})`);
        }

        // 合并分片
        if (!isUploading) throw new Error('用户取消了上传');
        showProgressText('合并分片中...');
        const mergeResponse = await fetch(`${API_URL}/mergeChunks`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                fileName: file.name,
                fileMd5: fileHash,
                totalChunks: totalChunks,
                originalFilename: file.name,
                totalSize: file.size
            })
        });

        if (!mergeResponse.ok) {
            throw new Error(`合并分片失败: ${mergeResponse.status}`);
        } else {
            const resultData = await mergeResponse.json();
            // 处理400或500错误状态码
            if (resultData.code === 400 || resultData.code === 500) {
                throw new Error(resultData.message || `合并分片失败: ${resultData.code}`);
            }
        }

        showStatusMessage('文件上传成功');
        showProgressText('上传完成');
        cancelBtn.style.display = 'none';
        fetchFileList();
    } catch (error) {
        showStatusMessage('上传失败: ' + error.message, true);
        // 隐藏取消按钮
        if (cancelBtn) {
            cancelBtn.style.display = 'none';
        }
    }
    // 重置上传状态
    isUploading = true;
}

// 计算文件哈希
async function calculateFileHash(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const wordArray = CryptoJS.lib.WordArray.create(e.target.result);
                const hash = CryptoJS.MD5(wordArray).toString();
                resolve(hash);
            } catch (error) {
                reject(error);
            }
        };
        reader.onerror = (e) => {
            reject(new Error('读取文件失败'));
        };
        reader.readAsArrayBuffer(file);
    });
}

// 预览文件
function previewFile(fileId) {
    const modal = document.getElementById('previewModal');
    const previewContent = document.getElementById('previewContent');
    
    // 根据文件类型设置预览内容
    const file = fileList.find(f => f.id === fileId);
    if (!file) {
        showStatusMessage('文件信息不存在', true);
        return;
    }
    
    if (file.fileType === 'Image') {
        previewContent.innerHTML = `<img src="${API_URL}/preview/${fileId}" class="preview-image">`;
    } else if (file.fileType === 'PDF') {
        previewContent.innerHTML = `<iframe src="${API_URL}/preview/${fileId}" class="preview-document"></iframe>`;
    } else {
        previewContent.innerHTML = `<div style="padding: 20px; text-align: center;">
            <i class="bi ${getFileIcon(file.fileType, file.fileExt)}" style="font-size: 48px;"></i>
            <p>不支持预览此文件类型</p>
            <a href="${API_URL}/download/${fileId}" class="btn btn-primary mt-3" target="_blank">下载文件</a>
        </div>`;
    }
    
    modal.style.display = 'block';
}

// 关闭预览
function closePreview() {
    document.getElementById('previewModal').style.display = 'none';
}

// 删除文件
async function deleteFile(fileId) {
    if (!confirm(`确定要删除此文件吗？`)) {
        return;
    }

    try {
        const response = await fetch(`${API_URL}/${fileId}`, {
            method: 'DELETE'
        });

        if (!response.ok) {
            throw new Error('删除失败');
        }

        const result = await response.json();
        if (result.code === 200) {
            showStatusMessage('文件删除成功');
            fetchFileList();
        } else {
            throw new Error(result.message || '删除失败');
        }
    } catch (error) {
        showStatusMessage('删除失败: ' + error.message, true);
    }
}

// 下载文件
function downloadFile(fileId) {
    window.open(`${API_URL}/download/${fileId}`, '_blank');
}

// 搜索文件
function searchFiles() {
    const searchTerm = document.getElementById('searchInput').value.toLowerCase();
    applyFilters(searchTerm);
}

// 显示选中文件的预览
function showSelectedFilePreview(file) {
    // 创建或获取预览区域
    let previewArea = document.getElementById('selectedFilePreview');
    if (!previewArea) {
        previewArea = document.createElement('div');
        previewArea.id = 'selectedFilePreview';
        previewArea.className = 'selected-file-preview';
        const uploadSection = document.getElementById('uploadSection');
        const progressContainer = document.querySelector('.progress-container');
        uploadSection.insertBefore(previewArea, progressContainer);
    }
    
    // 确定文件类型
    let fileType = 'Other';
    let fileIcon = 'bi-file-earmark';
    
    const fileExt = file.name.split('.').pop().toLowerCase();
    
    // 根据扩展名判断文件类型
    if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'].includes(fileExt)) {
        fileType = 'Image';
        fileIcon = 'bi-file-earmark-image';
    } else if (fileExt === 'pdf') {
        fileType = 'PDF';
        fileIcon = 'bi-file-earmark-pdf';
    } else if (['doc', 'docx', 'txt', 'rtf', 'md'].includes(fileExt)) {
        fileType = 'Document';
        fileIcon = 'bi-file-earmark-text';
    } else if (['zip', 'rar', '7z', 'tar', 'gz'].includes(fileExt)) {
        fileType = 'Archive';
        fileIcon = 'bi-file-earmark-zip';
    }
    
    // 创建预览内容
    let previewContent = `
        <div class="file-preview-header">
            <h5>已选择文件</h5>
            <button type="button" class="btn-close" onclick="clearFilePreview()"></button>
        </div>
        <div class="file-preview-content">
            <div class="file-preview-info">
                <i class="bi ${fileIcon} file-preview-icon"></i>
                <div class="file-preview-details">
                    <div class="file-preview-name">${file.name}</div>
                    <div class="file-preview-meta">${formatSize(file.size)} | ${fileType}</div>
                </div>
            </div>
    `;
    
    // 对于图片类型，添加图片预览
    if (fileType === 'Image') {
        const imageUrl = URL.createObjectURL(file);
        previewContent += `
            <div class="file-preview-image-container">
                <img src="${imageUrl}" class="file-preview-image" alt="${file.name}">
            </div>
        `;
    }
    
    previewContent += `</div>`;
    
    // 更新预览区域内容
    previewArea.innerHTML = previewContent;
    previewArea.style.display = 'block';
}

// 清除文件预览
function clearFilePreview() {
    const fileInput = document.getElementById('fileInput');
    fileInput.value = ''; // 清除文件输入
    
    const previewArea = document.getElementById('selectedFilePreview');
    if (previewArea) {
        previewArea.style.display = 'none';
    }
    
    // 清除进度和状态信息
    document.getElementById('progressText').style.display = 'none';
    document.getElementById('uploadProgress').style.display = 'none';
}